<?php

namespace app\model;

use think\Model;

class Category extends Model
{
    // 表名
    protected $name = 'categories';

    // 自动时间戳
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    // 字段类型转换
    protected $type = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'is_system' => 'boolean',
        'is_active' => 'boolean',
    ];

    // 关联用户
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // 关联账号
    public function accounts()
    {
        return $this->hasMany(Account::class);
    }

    // 获取用户分类（包含系统分类）
    public static function getUserCategories($userId)
    {
        return self::where(function ($query) use ($userId) {
            $query->where('user_id', $userId)
                ->whereOr('user_id', null);
        })
            ->where('is_active', 1)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
    }

    // 获取系统分类
    public static function getSystemCategories()
    {
        return self::where('is_system', 1)
            ->where('is_active', 1)
            ->order('sort', 'asc')
            ->select();
    }

    // 获取用户自定义分类
    public static function getUserCustomCategories($userId)
    {
        return self::where('user_id', $userId)
            ->where('is_system', 0)
            ->where('is_active', 1)
            ->order('sort', 'asc')
            ->order('id', 'asc')
            ->select();
    }

    // 检查分类名称是否存在
    public static function checkNameExists($name, $userId, $excludeId = null)
    {
        $query = self::where('name', $name)
            ->where(function ($query) use ($userId) {
                $query->where('user_id', $userId)
                    ->whereOr('user_id', null);
            });

        if ($excludeId) {
            $query->where('id', '<>', $excludeId);
        }

        return $query->find();
    }

    // 获取分类下的账号数量
    public function getAccountCountAttr()
    {
        return $this->accounts()->count();
    }

    // 获取最大排序值
    public static function getMaxSort($userId)
    {
        return self::where('user_id', $userId)->max('sort') ?: 0;
    }

    // 复制系统分类给用户
    public static function copySystemCategoriesToUser($userId)
    {
        $systemCategories = self::getSystemCategories();
        $userCategories = [];

        foreach ($systemCategories as $category) {
            $userCategories[] = [
                'user_id' => $userId,
                'name' => $category->name,
                'icon' => $category->icon,
                'color' => $category->color,
                'description' => $category->description,
                'sort' => $category->sort,
                'is_system' => 0,
                'is_active' => 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];
        }

        if ($userCategories) {
            return self::insertAll($userCategories);
        }

        return true;
    }
}